package com.yifeng.repo.base.utils.lbs;

import java.util.Arrays;

/**
 * Created by daibing on 2018/11/5.
 */
public class GpsHelper {

    private static final double PI = 3.14159265358979324 * 3000.0 / 180.0;

    public static double[] gaode2Baidu(double gdLon, double gdLat) {
        double[] baiduLatLon = new double[2];
        double x = gdLon;
        double y = gdLat;
        double z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * PI);
        double theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * PI);
        baiduLatLon[0] = z * Math.cos(theta) + 0.0065;
        baiduLatLon[1] = z * Math.sin(theta) + 0.006;
        return baiduLatLon;
    }

    public static double[] baidu2Gaode(double bdLat, double bdLon) {
        double[] gaodeLatLon = new double[2];
        double x = bdLon - 0.0065, y = bdLat - 0.006;
        double z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * PI);
        double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * PI);
        gaodeLatLon[0] = z * Math.cos(theta);
        gaodeLatLon[1] = z * Math.sin(theta);
        return gaodeLatLon;
    }

    /**
     * 赤道半径(google map, 单位m)
     */
    private static final double EARTH_RADIUS = 6378137;

    /**
     * 基于googleMap中的算法得到两经纬度之间的距离,计算精度与谷歌地图的距离精度差不多，相差范围在0.2米以下
     * @param lon1 第一点的精度
     * @param lat1 第一点的纬度
     * @param lon2 第二点的精度
     * @param lat2 第二点的纬度
     * @return 返回的距离，单位km
     */
    public static double getDistance(double lon1, double lat1, double lon2, double lat2) {
        double radLat1 = rad(lat1);
        double radLat2 = rad(lat2);
        double a = radLat1 - radLat2;
        double b = rad(lon1) - rad(lon2);
        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
        s = s * EARTH_RADIUS;
        s = Math.round(s * 10000) / 10000;
        return s;
    }

    /**
     * 转化为弧度(rad)
     */
    private static double rad(double d) {
        return d * Math.PI / 180.0;
    }

    public static void main(String[] args) {
        String address = "湖南省长沙市岳麓区金洲大道68号益丰大药房3楼";
        double lat = 28.226631;
        double lon = 112.848164;
        double[] result = baidu2Gaode(lat, lon);
        System.out.println("result: " + Arrays.toString(result));
    }

}
